package controllers;

import models.*;
import play.mvc.Scope.Session;
import play.mvc.Controller.*;
import play.mvc.*;
import play.data.validation.*;
/**
 * @author Andriy
 */
/**
 * Overriding method authenticate(String login, String password) of class
 * from module "secure"
 */
public class Security extends /*Secure.Security*/Controller {
	/**
	 * This method makes validation of login and password and checks their
	 * combination in database.
	 *
	 * @param login    login, that was entered by provider.
	 * @param password the string of password, that was entered by provider..
	 */

	public static void authenticate(@Required String login,@Required String password, float pLat,float pLong) {
                        long provId = -1;
                        if (Validation.hasErrors()) {
                                renderJSON(provId);
                        }
                        provId = existsProv(login, password);
                        renderJSON(provId);
	}
	/**
	 * method check that login and password exists in DB
	 *
	 * @param login    login, that was entered by provider.
	 * @param password the string of password, that was entered by provider.
	 * @return true if provider exists and false in other case
	 */
	public static long existsProv(String login, String password) {
		/**
		 * Find provider by login
		 */
		Provs prov = Provs.find("byLogin", login).first();
		String encryptedPass = Encrypt.encrypt(password);

		/**
		 * if provider exists and correct his password
		 */
		if ((prov != null) && (prov.password.equals(encryptedPass))) {
			//save id of provider in session
			Session.current().put("provId", prov.id);
			return prov.id;
		} else {
			return -1;
		}
	}
	/**
	 *  This method called by user when it sign in web service.
	 *  @param deviceSn - code of user device
	 * */
	public static void userSignIn(@Required String deviceSn ){
		long userId = -1;
                if (!Validation.hasErrors()) {
                        Users user = Users.find("byDeviceSn",deviceSn).first();
                        if(user != null){
                                userId = user.id;
                                //Save id of user in session
                                Scope.Session.current().put("userId",userId);
                        }
                }
		StatusController.userDeclared(userId);
	}
}
